import React from 'react';
import {injectIntl, language} from './intl';
import PropTypes from 'prop-types';
import {Radio, Button, Form, Row, Col, Card, Spin, message, Table, Popconfirm, Modal, Icon, Tooltip, Divider} from 'antd';
import routes from './routes';
import {FORM_OPTIONS, FORM_ROW_OPTIONS, PAGE, TABLE, FIXED_COLUMN_WIDTH, DATE_FORMAT, PAGINATION_OPTIONS} from '../constants';
import {conventEnumValueToString, formatAmount, formatDateTime} from '../utils';
import WrappedSelect from '../common/WrappedSelect';
import {PERMISSION} from './constants';
import TextInput from 'Shared/components/TextInput';
import styles from './style.css';
import Return from '../common/Return';
import {validateAdd, renderBoolean} from './utils';
import InputAmount from '../common/InputAmount';
import {paymentType, transportType, partOrderPriceTerms, currency, packingType} from '../Enum';
import DealerSelectPanel from './DealerSelectPanel';
import PackingSelectPanel from './PackingSelectPanel';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import {uniq, maxBy} from 'lodash';
import Export from '../common/Export';
import {exportInfo} from './api';
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const sortByName = name => (a, b) => {
    if(a[name] && b[name])
        return a[name].localeCompare(b[name]);
    return 0;
};
const autosize = {minRows: 1};
const EMPTY_ARRAY = [];
const flagOptions = [
    {
        text: renderBoolean(true),
        value: Number(true),
    },
    {
        text: renderBoolean(false),
        value: Number(false),
    },
];
const rowKey = record => `${record.packingListId}${record.partCode}`;
export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showPanel: false,
        isPrevError: false,
        isPrevLoading: false,
        isFirst: true,
        isShipLoading: false,
        isShipError: false,
        isFeeLoading: false,
        isFeeError: false,
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };

    handlePriceTermChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onPriceTermsChange(name, value);
    }
    handleStatusChange = e => {
        const {name, value} = e.target;
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        const {rebateFee = 0, lockedFee = 0} = this.props.conditions;
        const fee = rebateFee - lockedFee;
        if(value)
            return Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'add.handleDealerChange.title',
                    defaultMessage: '可用返利余额为{fee},请确认是否强制使用'
                }, {fee}),
                onOk: () => {
                    this.props.onSelectCoerciveBonus();
                }
            });
        this.props.onConditionsChange(name, value);
    }
    showPanel = () => {
        this.setState({
            showPanel: !this.state.showPanel
        });
    }

   
    onSelectPacking = data => {
        this.setState({
            showPanel: false
        });
        if(data.length) {
            this.props.onSelectDetails(data);
            this.onSearchPaymentType();
        }
    }

    onSearchPaymentType = () => {
        if(!this.props.id && this.state.isFirst && !this.props.conditions.paymentType) {
            this.setState({isShipLoading: true});
            return this.props.onSearchPaymentType().then(success => {
                this.setState({
                    isShipLoading: false,
                    isShipError: !success,
                    isFirst: !success
                });
            });
        }
    }

    onSearchRebateFee = () => {
        if(!this.props.id && this.props.conditions.dealerId) {
            this.setState({isFeeLoading: true});
            return this.props.onSearchRebateFee().then(success => {
                this.setState({
                    isFeeLoading: false,
                    isFeeError: !success,
                });
            });
        }
    }

    onClickDelete = e => {
        const {id} = e.target.dataset;
        this.props.onDeleteDetail(id);
    };

    onClickAdd = () => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        if(!this.props.id && !this.props.conditions.dealerId)
            return message.warn(this.props.intl.formatMessage({
                id: 'queryPanel.message.dealerId',
                defaultMessage: '请先选择总代'
            }));
        this.setState({
            showPanel: true
        });
    }
    
    onSubmit = () => {
        const result = validateAdd(this.props.conditions, this.props.id);
        if(result) {
            this.setState({
                isValidate: true,
            });
            return message.warn(result);
        }
        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    onSelectDealer = data => {
        const {packingLists = [], dealerId} = this.props.conditions;
        if(!data.id || data.id === dealerId)
            return;
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        if(packingLists.length && data.id !== dealerId)
            return Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'add.handleCompanyChange.title',
                    defaultMessage: '变更总代将会清空清单，是否变更？'
                }),
                onOk: () => {
                    this.setState({isPrevLoading: true});
                    return this.props.onSelectDealer(data).then(success => {
                        this.setState({
                            isPrevLoading: false,
                            isPrevError: !success
                        });
                        return this.onSearchRebateFee();
                    });
                },
            });
        this.setState({isPrevLoading: true});
        return this.props.onSelectDealer(data).then(success => {
            this.setState({
                isPrevLoading: false,
                isPrevError: !success
            });
            return this.onSearchRebateFee();
        });
    }
    
    onSearchPrevOrder = () => {
        this.setState({isPrevLoading: true});
        return this.props.onSearchPrevOrder().then(success => {
            this.setState({
                isPrevLoading: false,
                isPrevError: !success
            });
        });
    }

    onPackingTableFooter = () => {
        const {packingLists = []} = this.props.conditions;
        const {totalVolume, totalNetWeight, totalGrossWeight} = packingLists.reduce((a, b) => ({
            totalVolume: a.totalVolume + b.volume,
            totalNetWeight: a.totalNetWeight + b.netWeight,
            totalGrossWeight: a.totalGrossWeight + b.grossWeight,
        }), {
            totalVolume: 0,
            totalNetWeight: 0,
            totalGrossWeight: 0
        });
        const length = packingLists.length;

        return (<React.Fragment>
            <span>{`${this.props.intl.formatMessage({
                id: 'add.footer.totalVolume',
                defaultMessage: '总体积（m³）:'
            })}${formatAmount(totalVolume)}`}</span>
            <Divider type="vertical" />
            <span>{`${this.props.intl.formatMessage({
                id: 'add.footer.totalNetWeight',
                defaultMessage: '总净重（kg）:'
            })}${formatAmount(totalNetWeight)}`}</span>
            <Divider type="vertical" />
            <span>{`${this.props.intl.formatMessage({
                id: 'add.footer.totalGrossWeight',
                defaultMessage: '总毛重（kg）:'
            })}${formatAmount(totalGrossWeight)}`}</span>
            <Divider type="vertical" />
            <span>{`${this.props.intl.formatMessage({
                id: 'add.footer.length',
                defaultMessage: '总包装数:'
            })}${length}`}</span>
        </React.Fragment>);
    }

    onDetailTableFooter = () => {
        const {details = []} = this.props.conditions;
        const {totalAmounts, totalNetWeight, totalGrossWeight, totalNum} = details.reduce((a, b) => ({
            totalAmounts: a.totalAmounts + (b.totalAmount || 0),
            totalNetWeight: a.totalNetWeight + b.netWeight,
            totalGrossWeight: a.totalGrossWeight + b.grossWeight,
            totalNum: a.totalNum + b.quantity,
        }), {
            totalAmounts: 0,
            totalNetWeight: 0,
            totalNum: 0,
            totalGrossWeight: 0
        });
        const totalKind = details.length;
        return (<React.Fragment>
            <span>{`${this.props.intl.formatMessage({
                id: 'add.footer.totalAmounts',
                defaultMessage: '总价:'
            })}${formatAmount(totalAmounts)}`}</span>
            <Divider type="vertical" />
            <span>{`${this.props.intl.formatMessage({
                id: 'add.footer.totalNetWeight',
                defaultMessage: '总净重（kg）:'
            })}${formatAmount(totalNetWeight)}`}</span>
            <Divider type="vertical" />
            <span>{`${this.props.intl.formatMessage({
                id: 'add.footer.totalGrossWeight',
                defaultMessage: '总毛重（kg）:'
            })}${formatAmount(totalGrossWeight)}`}</span>
            <Divider type="vertical" />
            <span>{`${this.props.intl.formatMessage({
                id: 'add.footer.totalKind',
                defaultMessage: '总品种数:'
            })}${totalKind}`}</span>
            <Divider type="vertical" />
            <span>{`${this.props.intl.formatMessage({
                id: 'add.footer.totalNum',
                defaultMessage: '总数量:'
            })}${totalNum}`}</span>
            
        </React.Fragment>);
    }
    
    onClickExport = () => {
        const {packingLists = [], diffRebate} = this.props.conditions;
        if(!packingLists.length)
            return message.warn(this.props.intl.formatMessage({
                id: 'add.export.message',
                defaultMessage: '箱单发票备件清单不能为空'
            }));
        return exportInfo({
            packingListIds: packingLists.map(item => item.id),
            rebate: diffRebate
        });
    }
    render() {
        const {
            details = [], packingLists = [],
            lockedFee = 0, bonusTotal = 0, totalFee = 0, bonusAmount = 0,
        } = this.props.conditions;
        const packingColumns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.pickingListCodes',
                    defaultMessage: '备料单号'
                }),
                dataIndex: 'pickingListCodes',
                render: text => <Ellipsis tooltip fullWidthRecognition length={36}>{text}</Ellipsis>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.palletCodes',
                    defaultMessage: '托盘号'
                }),
                dataIndex: 'palletCodes',
                render: text => <Ellipsis tooltip fullWidthRecognition length={36}>{text}</Ellipsis>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.packingType',
                    defaultMessage: '包装类型'
                }),
                dataIndex: 'packingType',
                sorter: sortByName('packingType'),
                render: text => conventEnumValueToString(packingType, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.container',
                    defaultMessage: '包装规格'
                }),
                dataIndex: 'container',
            },
            {
                title: <div className={styles.column}>{this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.length',
                    defaultMessage: '长'
                })}<br/>{this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.mm',
                    defaultMessage: '（mm）'
                })}</div>,
                dataIndex: 'length',
                width: 80
            },
            {
                title: <div className={styles.column}>{this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.width',
                    defaultMessage: '宽'
                })}<br/>{this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.mm',
                    defaultMessage: '（mm）'
                })}</div>,
                dataIndex: 'width',
                width: 80
            },
            {
                title: <div className={styles.column}>{this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.height',
                    defaultMessage: '高'
                })}<br/>{this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.mm',
                    defaultMessage: '（mm）'
                })}</div>,
                dataIndex: 'height',
                width: 80
            },
            {
                title: <div className={styles.column}>{this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.volume',
                    defaultMessage: '体积'
                })}<br/>{this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.m3',
                    defaultMessage: '（m3）'
                })}</div>,
                dataIndex: 'volume',
                width: 80
            },
            {
                title: <div className={styles.column}>{this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.netWeight',
                    defaultMessage: '净重'
                })}<br/>{this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.kg',
                    defaultMessage: '（kg）'
                })}</div>,
                dataIndex: 'netWeight',
                width: 80
            },
            {
                title: <div className={styles.column}>{this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.grossWeight',
                    defaultMessage: '毛重'
                })}<br/>{this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.kg',
                    defaultMessage: '（kg）'
                })}</div>,
                dataIndex: 'grossWeight',
                width: 80
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.containerNo',
                    defaultMessage: '柜图号'
                }),
                dataIndex: 'containerNo',
                sorter: sortByName('containerNo')
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.packingColumns.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark',
            },

            {
                title: packingLists.length ? (<Popconfirm
                    placement="top"
                    key="deleteAll"
                    onConfirm={this.props.onDeleteAll}
                    title={this.props.intl.formatMessage({
                        id: 'add.popconfirm.delete.message',
                        defaultMessage: '是否确认清空?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'add.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'add.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}>
                    <a key="clearBtn">
                        {this.props.intl.formatMessage({
                            id: 'add.materials.clearBtn',
                            defaultMessage: '清空'
                        })}
                    </a>
                </Popconfirm>)
                    : (
                        <a key="clearBtn">
                            {this.props.intl.formatMessage({
                                id: 'add.materials.clearBtn',
                                defaultMessage: '清空'
                            })}
                        </a>
                    ),
                dataIndex: 'action',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => <a onClick={this.onClickDelete} key="delete" data-id={record.id}>
                    {this.props.intl.formatMessage({
                        id: 'add.delete',
                        defaultMessage: '删除'
                    })}
                </a>
            }
        ];
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.partSaleOrderCode',
                    defaultMessage: '订单号'
                }),
                dataIndex: 'partSaleOrderCode',
                sorter: sortByName('partSaleOrderCode')
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.pickingListCode',
                    defaultMessage: '备料单号'
                }),
                dataIndex: 'pickingListCode',
                sorter: sortByName('pickingListCode')
            }, {
                title: this.props.intl.formatMessage({
                    id: 'add.column.palletCode',
                    defaultMessage: '托盘号'
                }),
                dataIndex: 'palletCode',
                sorter: sortByName('palletCode')
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.partCode',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'partCode',
                sorter: sortByName('partCode')
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.partName',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'partName',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.quantity',
                    defaultMessage: '数量'
                }),
                dataIndex: 'quantity',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.price',
                    defaultMessage: '单价'
                }),
                dataIndex: 'price',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.pricingDate',
                    defaultMessage: '定价日期'
                }),
                dataIndex: 'pricingDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.totalAmount',
                    defaultMessage: '总价'
                }),
                dataIndex: 'totalAmount',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.perNetWeight',
                    defaultMessage: '单位净重'
                }),
                dataIndex: 'perNetWeight',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.netWeight',
                    defaultMessage: '净重'
                }),
                dataIndex: 'netWeight',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.perGrossWeight',
                    defaultMessage: '单位毛重'
                }),
                dataIndex: 'perGrossWeight',
                render: text => text ? text.toFixed(3) : text
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.grossWeight',
                    defaultMessage: '毛重'
                }),
                dataIndex: 'grossWeight',
                render: text => text ? text.toFixed(3) : text
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.oldPartCode',
                    defaultMessage: '被替换备件编号'
                }),
                dataIndex: 'oldPartCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.discountPrice',
                    defaultMessage: '折扣后单价'
                }),
                dataIndex: 'discountPrice',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.discountAmount',
                    defaultMessage: '折扣后总价'
                }),
                dataIndex: 'discountAmount',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
        ];

        const dealerInfo = this.props.conditions.dealerId ? {
            id: this.props.conditions.dealerId,
            code: this.props.conditions.dealerCode,
            name: this.props.conditions.dealerName
        } : null;
        const currentSelectRowKeys = packingLists.map(item => item.id);
        const dealerComp = this.props.conditions.brandId ? (<DealerSelectPanel
            value={dealerInfo}
            brandId={this.props.conditions.brandId}
            onSelect={this.onSelectDealer} />) : (<TextInput name="dealerId"
            value={''} disabled placeholder={this.props.intl.formatMessage({
                id: 'add.dealerComp.placeholder',
                defaultMessage: '请先选择品牌'
            })} />);
        const isShowCoerciveBonus = this.props.id ? Boolean(
            !this.props.conditions.isBonusNumber &&
            lockedFee === 0 &&
            this.props.conditions.rebateFee < bonusTotal
        ) : Boolean(
            lockedFee === 0 &&
            this.props.conditions.rebateFee < bonusTotal
        );
        return (
            <div className={styles.detail}>
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'add.stock.modal.title',
                        defaultMessage: '备件包装箱单查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showPanel}
                    onCancel={this.showPanel}>
                    <PackingSelectPanel
                        dealerId={this.props.conditions.dealerId}
                        currentSelectRowKeys={currentSelectRowKeys}
                        onSelect={this.onSelectPacking} />
                </Modal>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'add.card.buyerBaseInfo.title',
                                defaultMessage: '买方基础信息'
                            })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.code',
                                            defaultMessage: '发票号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.id ? this.props.conditions.code : this.props.intl.formatMessage({
                                            id: 'add.form.code.noData',
                                            defaultMessage: '<尚未生成>'
                                        })}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.brandId ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.brandId',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {this.props.id ? <span className="value-font">{`(${this.props.conditions.brandCode})${this.props.conditions.brandName}`}</span>
                                            : <WrappedSelect
                                                name="brandId"
                                                allowClear={false}
                                                value={this.props.conditions.brandId}
                                                options={this.props.brands}
                                                onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={!this.props.id && this.state.isValidate && !this.props.conditions.dealerId ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {this.props.id
                                            ? <span className="value-font">{this.props.conditions.dealerCode}</span>
                                            : dealerComp}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.receiverCode',
                                            defaultMessage: '送达方编号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.receiverCode}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.country',
                                            defaultMessage: '国家'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.country}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.currency',
                                            defaultMessage: '结算币种'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{conventEnumValueToString(currency, this.props.conditions.currency)}</span>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'add.form.partSaleOrderCodes',
                                        defaultMessage: '订单编号'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    {this.props.conditions.partSaleOrderCodes && this.props.conditions.partSaleOrderCodes.length > 100 ? <Ellipsis length={100} tooltip>
                                        {this.props.conditions.partSaleOrderCodes}
                                    </Ellipsis> : this.props.conditions.partSaleOrderCodes}
                                    
                                </FormItem>
                            </Row>
                        </Card>
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'add.card.sellerContact.title',
                                defaultMessage: '卖方联系方式'
                            })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.seller ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.seller',
                                            defaultMessage: '卖方名称'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="seller"
                                            value={this.props.conditions.seller} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.sellerNumber ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.sellerNumber',
                                            defaultMessage: '卖方电话'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="sellerNumber"
                                            value={this.props.conditions.sellerNumber} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.sellerFAX',
                                            defaultMessage: '卖方传真'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="sellerFAX"
                                            value={this.props.conditions.sellerFAX} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <FormItem
                                    validateStatus={this.state.isValidate && !this.props.conditions.sellerAddress ? 'error' : null}
                                    required
                                    label={this.props.intl.formatMessage({
                                        id: 'add.form.sellerAddress',
                                        defaultMessage: '卖方地址'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    <TextInput name="sellerAddress"
                                        value={this.props.conditions.sellerAddress} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Row>
                        </Card>
                        <Spin spinning={this.state.isPrevLoading}>
                            <Card
                                title={this.state.isPrevError ? (<Tooltip title={this.props.intl.formatMessage({
                                    id: 'add.card.icon.title',
                                    defaultMessage: '点击图标重新获取买方联系方式和发运付款信息'
                                })}>
                                    {this.props.intl.formatMessage({
                                        id: 'add.card.buyerContact.title',
                                        defaultMessage: '买方联系方式'
                                    })}
                                    {'  '}
                                    <Icon className={styles.blue} onClick={this.onSearchPrevOrder} type="reload" />
                                </Tooltip>)
                                    : this.props.intl.formatMessage({
                                        id: 'add.card.buyerContact.title',
                                        defaultMessage: '买方联系方式'
                                    })}>
                                <Row>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            validateStatus={this.state.isValidate && !this.props.conditions.buyer ? 'error' : null}
                                            required
                                            label={this.props.intl.formatMessage({
                                                id: 'add.form.buyer',
                                                defaultMessage: '买方名称'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <TextInput name="buyer"
                                                value={this.props.conditions.buyer} onBlur={this.handleFilterChange} />
                                        </FormItem>
                                    </Col>

                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            validateStatus={this.state.isValidate && !this.props.conditions.buyerNumber ? 'error' : null}
                                            required
                                            label={this.props.intl.formatMessage({
                                                id: 'add.form.buyerNumber',
                                                defaultMessage: '联系电话'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <TextInput name="buyerNumber"
                                                value={this.props.conditions.buyerNumber} onBlur={this.handleFilterChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'add.form.buyerFAX',
                                                defaultMessage: '买方传真'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <TextInput name="buyerFAX"
                                                value={this.props.conditions.buyerFAX} onBlur={this.handleFilterChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            validateStatus={this.state.isValidate && !this.props.conditions.buyerCantact ? 'error' : null}
                                            required
                                            label={this.props.intl.formatMessage({
                                                id: 'add.form.buyerCantact',
                                                defaultMessage: '买方联系人'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <TextInput name="buyerCantact"
                                                value={this.props.conditions.buyerCantact} onBlur={this.handleFilterChange} />
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.buyerAddress ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.buyerAddress',
                                            defaultMessage: '买方地址'
                                        })}
                                        {...FORM_ROW_OPTIONS.item}>
                                        <TextInput name="buyerAddress"
                                            value={this.props.conditions.buyerAddress} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Row>
                            </Card>
                            <Card
                                title={this.props.intl.formatMessage({
                                    id: 'add.card.payment.title',
                                    defaultMessage: '发运付款信息'
                                })}>
                                <Row>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            validateStatus={this.state.isValidate && !this.props.conditions.origin ? 'error' : null}
                                            required
                                            label={this.props.intl.formatMessage({
                                                id: 'add.form.origin',
                                                defaultMessage: '起运地'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <TextInput name="origin"
                                                value={this.props.conditions.origin} onBlur={this.handleFilterChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            validateStatus={this.state.isValidate && !this.props.conditions.destination ? 'error' : null}
                                            required
                                            label={this.props.intl.formatMessage({
                                                id: 'add.form.destination',
                                                defaultMessage: '目的地'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <TextInput name="destination"
                                                value={this.props.conditions.destination} onBlur={this.handleFilterChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            validateStatus={this.state.isValidate && !this.props.conditions.paymentType ? 'error' : null}
                                            required
                                            label={this.state.isShipError && !this.props.conditions.paymentType ? (<Tooltip title={this.props.intl.formatMessage({
                                                id: 'add.card.paymentIcon.title',
                                                defaultMessage: '点击图标重新获取付款方式'
                                            })}>
                                                {this.props.intl.formatMessage({
                                                    id: 'queryPanel.form.paymentType',
                                                    defaultMessage: '付款方式'
                                                })}
                                                {'  '}
                                                <Icon className={styles.blue} onClick={this.onSearchPaymentType} type="reload" />
                                            </Tooltip>)
                                                : this.props.intl.formatMessage({
                                                    id: 'queryPanel.form.paymentType',
                                                    defaultMessage: '付款方式'
                                                })}
                                            {...FORM_OPTIONS.item}>
                                            <Spin spinning={this.state.isShipLoading}>
                                                <WrappedSelect
                                                    name="paymentType"
                                                    value={this.props.conditions.paymentType}
                                                    options={paymentType.toList(language)}
                                                    onChange={this.handleFilterChange} />
                                            </Spin>
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            validateStatus={this.state.isValidate && !this.props.conditions.priceTerms ? 'error' : null}
                                            required
                                            label={this.props.intl.formatMessage({
                                                id: 'queryPanel.form.priceTerms',
                                                defaultMessage: '价格条款'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <WrappedSelect
                                                name="priceTerms"
                                                allowClear
                                                value={this.props.conditions.priceTerms}
                                                options={partOrderPriceTerms.toList(language)}
                                                onChange={this.handlePriceTermChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            validateStatus={this.state.isValidate && !this.props.conditions.shipmentType ? 'error' : null}
                                            required
                                            label={this.props.intl.formatMessage({
                                                id: 'queryPanel.form.shipmentType',
                                                defaultMessage: '运输方式'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <WrappedSelect
                                                name="shipmentType"
                                                allowClear
                                                value={this.props.conditions.shipmentType}
                                                options={transportType.toList(language)}
                                                onChange={this.handleFilterChange} />
                                        </FormItem>
                                    </Col>
                                    {this.props.conditions.shipmentType === transportType.快递 && <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'queryPanel.form.carrierId',
                                                defaultMessage: '快递公司'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <WrappedSelect
                                                name="carrierId"
                                                allowClear
                                                value={this.props.conditions.carrierId}
                                                options={this.props.carriers}
                                                onChange={this.handleFilterChange} />
                                        </FormItem>
                                    </Col>}
                                </Row>
                            </Card>
                        </Spin>
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'add.card.fee.title',
                                defaultMessage: '运保费和折扣信息'
                            })}>
                            <Row>

                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.itemCount',
                                            defaultMessage: '备件品种数'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.itemCount}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.totalQuantity',
                                            defaultMessage: '备件总数量'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.totalQuantity}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.totalAmount',
                                            defaultMessage: '备件总金额'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{formatAmount(this.props.conditions.totalAmount)}</span>
                                    </FormItem>
                                </Col>
                                {this.props.conditions.priceTerms === partOrderPriceTerms.CPT ||
                                    this.props.conditions.priceTerms === partOrderPriceTerms.CIF ||
                                    this.props.conditions.priceTerms === partOrderPriceTerms.CFR ||
                                    this.props.conditions.priceTerms === partOrderPriceTerms.CIP
                                    ? <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            validateStatus={this.state.isValidate && !this.props.conditions.freight ? 'error' : null}
                                            required
                                            label={this.props.intl.formatMessage({
                                                id: 'add.form.freight',
                                                defaultMessage: '运费'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <InputAmount
                                                min={0}
                                                name="freight"
                                                value={this.props.conditions.freight}
                                                onBlur={this.handleFilterChange} />
                                        </FormItem>
                                    </Col> : null}
                                {this.props.conditions.priceTerms === partOrderPriceTerms.CIF ||
                                    this.props.conditions.priceTerms === partOrderPriceTerms.CIP
                                    ? <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            validateStatus={this.state.isValidate && !this.props.conditions.insurance ? 'error' : null}
                                            required
                                            label={this.props.intl.formatMessage({
                                                id: 'add.form.insurance',
                                                defaultMessage: '保费'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <InputAmount
                                                min={0}
                                                name="insurance"
                                                value={this.props.conditions.insurance}
                                                onBlur={this.handleFilterChange} />
                                        </FormItem>
                                    </Col> : null}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.discountAmount',
                                            defaultMessage: '折扣金额'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <InputAmount
                                            min={-Infinity}
                                            name="discountAmount"
                                            value={this.props.conditions.discountAmount}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.otherAmount',
                                            defaultMessage: '其他金额'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <InputAmount
                                            min={-Infinity}
                                            name="otherAmount"
                                            value={this.props.conditions.otherAmount}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.claimAmount',
                                            defaultMessage: '索赔金额'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <InputAmount
                                            min={-Infinity}
                                            name="claimAmount"
                                            value={this.props.conditions.claimAmount}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem className={styles.multiLabel}
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.differentAmount',
                                            defaultMessage: '报关差异金额'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <InputAmount
                                            min={-Infinity}
                                            name="differentAmount"
                                            value={this.props.conditions.differentAmount}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && typeof this.props.conditions.isBonusNumber !== 'number' ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.isBonusNumber',
                                            defaultMessage: '是否使用返利'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedSelect
                                            allowClear
                                            name="isBonusNumber"
                                            value={this.props.conditions.isBonusNumber}
                                            options={flagOptions}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && typeof this.props.conditions.isBonusNumber !== 'number' ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.isCoerciveBonus',
                                            defaultMessage: '强制使用返利'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <RadioGroup disabled={!isShowCoerciveBonus} name="isCoerciveBonus" onChange={this.handleStatusChange} value={this.props.conditions.isCoerciveBonus}>
                                            <Radio value={true}>{this.props.intl.formatMessage({
                                                id: 'add.form.yes',
                                                defaultMessage: '是'
                                            })}</Radio>
                                            <Radio value={false}>{this.props.intl.formatMessage({
                                                id: 'add.form.no',
                                                defaultMessage: '否'
                                            })}</Radio>
                                        </RadioGroup>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.bonusAmount',
                                            defaultMessage: '奖励金额'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{formatAmount(this.props.conditions.bonusAmount)}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.rebateFee',
                                            defaultMessage: '返利余额'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {this.props.id ? <span className="value-font">{formatAmount(this.props.conditions.rebateFee)}</span> : <Spin spinning={this.state.isFeeLoading}>
                                            {this.state.isFeeError
                                                ? <span className="value-font">{this.props.intl.formatMessage({
                                                    id: 'add.form.rebateFee.span',
                                                    defaultMessage: '点击图标重新获取返利余额'
                                                })}
                                                {'  '}
                                                <Icon className={styles.blue} onClick={this.onSearchRebateFee} type="reload" /></span>
                                                : <span className="value-font">{formatAmount(this.props.conditions.rebateFee)}</span>}
                                        </Spin>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.lockedFee',
                                            defaultMessage: '锁定金额'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <Spin spinning={this.state.isFeeLoading}>
                                            {this.state.isFeeError
                                                ? <span className="value-font">{this.props.intl.formatMessage({
                                                    id: 'add.form.lockedFee.span',
                                                    defaultMessage: '点击图标重新获取锁定金额'
                                                })}
                                                {'  '}
                                                <Icon className={styles.blue} onClick={this.onSearchRebateFee} type="reload" /></span>
                                                : <span className="value-font">{formatAmount(this.props.conditions.lockedFee)}</span>}
                                        </Spin>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.totalDiscount',
                                            defaultMessage: '折扣总金额'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{formatAmount(this.props.conditions.totalDiscount)}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.totalFee',
                                            defaultMessage: '总金额'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{formatAmount(this.props.conditions.totalFee)}</span>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <FormItem
                                    validateStatus={this.state.isValidate && this.props.conditions.totalDiscount !== 0 && !this.props.conditions.discountReason ? 'error' : null}
                                    required={this.props.conditions.totalDiscount !== 0}
                                    label={this.props.intl.formatMessage({
                                        id: 'add.form.discountReason',
                                        defaultMessage: '折扣原因'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    <TextInput type="textarea" name="discountReason" autosize={autosize}
                                        value={this.props.conditions.discountReason} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Row>
                        </Card>
                    </Form>
                    <Card
                        extra={<span className={styles.optionBtn}>
                            <Button key="addBtn" size="small" onClick={this.onClickAdd}>
                                {this.props.intl.formatMessage({
                                    id: 'add.form.addBtn',
                                    defaultMessage: '新增'
                                })}
                            </Button>
                        </span>}
                        title={this.props.intl.formatMessage({
                            id: 'add.packlingLists.title',
                            defaultMessage: '箱单发票装箱单'
                        })}
                        bordered={false}>
                        <Table className="white-space-nowrap"
                            rowKey="id"
                            columns={packingColumns}
                            footer={this.onPackingTableFooter}
                            pagination={false}
                            dataSource={packingLists}
                            {...TABLE} />
                    </Card>
                    <Card
                        title={this.props.intl.formatMessage({
                            id: 'add.details.title',
                            defaultMessage: '箱单发票备件清单'
                        })}

                        extra={this.props.id ? null
                            : <Export key="export" size="small" exportRequest={this.onClickExport} />}
                        bordered={false}>
                        <Table className="white-space-nowrap"
                            rowKey={rowKey}
                            columns={columns}
                            pagination={false}
                            footer={this.onDetailTableFooter}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    {this.props.submitable && (
                        <Card type="inner">
                            <Row>
                                <Col className="col-align-right">
                                    <Button
                                        key="submit"
                                        type="primary"
                                        loading={this.state.loading}
                                        onClick={this.onSubmit}>
                                        {this.props.intl.formatMessage({
                                            id: 'add.btn.save',
                                            defaultMessage: '保存'
                                        })}
                                    </Button>
                                </Col>
                            </Row>
                        </Card>
                    )}
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    conditions: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onPriceTermsChange: PropTypes.func.isRequired,
    onSearchPaymentType: PropTypes.func.isRequired,
    onSearchPrevOrder: PropTypes.func.isRequired,
    onSearchRebateFee: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object,
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    clearData,
    tableSearch,
    onClickUpdate,
    getDetail,
    deleteAllDetail,
    deleteDetail,
    selectCountry,
    selectPacking,
    getPrevInfo,
    getPaymentType,
    getFee,
    selectCoerciveBonus,
    savePriceTermsCondition,
} from './actions';
import {createSelector} from 'reselect';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';

const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    (state, ownProps) => ownProps.id,
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, id, detail) => {
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        const submitable = id ? data.includes(PERMISSION.update) && options.includes(PERMISSION.update)
            : data.includes(PERMISSION.add);
        return submitable;
    }
);

const getConditions = createSelector(
    (state, ownProps) => getSubmitData(state, ownProps),
    (state, ownProps) => ownProps.id,
    (data, id) => {
        const {details = [], isCoerciveBonus = false,
            discountAmount = 0, otherAmount = 0, claimAmount = 0, differentAmount = 0, freight = 0, insurance = 0, rebateFee = 0,
            isBonusNumber,
            invoiceAmount = 0,
        } = data;
        const partSaleOrderCodes = uniq(details.map(item => item.partSaleOrderCode)).join(',');
        const partDetails = uniq(details.map(item => ({
            partCode: item.partCode,
            quantity: item.quantity,
            totalAmount: item.totalAmount,
        })));
        const itemCount = partDetails.length;
        const totalQuantity = partDetails.reduce((a, b) => a + b.quantity, 0);
        const totalAmount = partDetails.reduce((a, b) => a + b.totalAmount, 0);
        const bonusTotal = (totalAmount + discountAmount + otherAmount + claimAmount + differentAmount) * 0.1;
        const coerciveAmount = isCoerciveBonus ? rebateFee * -1 : bonusTotal * -1;
        const bonusAmount = isBonusNumber ? coerciveAmount : 0;
        const totalDiscount = discountAmount + otherAmount + claimAmount + differentAmount + bonusAmount;
        const totalFee = totalAmount + freight + insurance + totalDiscount;
        // 折扣率
        const positive = 1 + (totalDiscount / totalAmount);
        const diffRebate = totalDiscount && totalAmount ? positive : 1;
        const newDetails = details.map(item => ({
            ...item,
            discountPrice: item.price * diffRebate,
            discountAmount: item.price * diffRebate * item.quantity,
        }));
        if(id && newDetails.length) {
            const diffAmount = invoiceAmount - newDetails.reduce((a, b) => a + b.discountAmount, 0);
            const {discountAmount: maxAmount} = maxBy(newDetails, p => p.discountAmount) || {};
            const index = newDetails.findIndex(p => p.discountAmount === maxAmount);
            newDetails[index].discountAmount += diffAmount;
        }
        return {
            ...data,
            diffRebate,
            details: newDetails,
            partSaleOrderCodes,
            itemCount,
            totalQuantity,
            totalAmount,
            bonusAmount,
            bonusTotal,
            totalDiscount,
            totalFee,
            isCoerciveBonus,
        };
    }
);

const getBrandsData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return brands;
    }
);

const getCarriersData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const carriers = initData.carriers ? initData.carriers.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return carriers;
    }
);

const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state, ownProps),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    conditions: getConditions(state, ownProps),
    brands: getBrandsData(state),
    carriers: getCarriersData(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => {
        if(ownProps.id)
            return dispatch(getDetail(ownProps.id)).then(success => {
                if(success)
                    return dispatch(getFee(ownProps.id));
                return success;
            });
        return Promise.resolve(true);
    },
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onPriceTermsChange: (name, value) => dispatch(savePriceTermsCondition(name, value)),
    onSubmit: status =>
        dispatch(onClickUpdate(ownProps.id, status)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
    onDeleteAll: () => dispatch(deleteAllDetail()),
    onDeleteDetail: id => dispatch(deleteDetail(id)),
    onSelectDealer: data => {
        dispatch(selectCountry(data));
        return dispatch(getPrevInfo());
    },
    onSelectDetails: data => dispatch(selectPacking(data)),
    onSearchPrevOrder: () => dispatch(getPrevInfo()),
    onSearchPaymentType: () => dispatch(getPaymentType()),
    onSearchRebateFee: () => ownProps.id ? dispatch(getFee(ownProps.id)) : dispatch(getFee()),
    onSelectCoerciveBonus: () => dispatch(selectCoerciveBonus()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
